package com.wonders.healthcitydoctor.ui.base;


import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.wonders.healthcitydoctor.R;
import com.wonders.healthcitydoctor.util.LogUtil;
import com.wonders.healthcitydoctor.util.SPUtils;

import java.lang.ref.WeakReference;
import java.util.List;

import me.yokeyword.fragmentation.SupportFragment;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 懒加载
 * Created by YoKeyword on 16/6/5.
 */
public abstract class BaseMainFragment extends SupportFragment implements  EasyPermissions.PermissionCallbacks{
    protected String TAG=this.getClass().getSimpleName();
    // 再点一次退出程序时间设置
    private static final long WAIT_TIME = 2000L;
    private long TOUCH_TIME = 0;
    protected Activity mActivity;
    protected boolean mIsLoadedData = false;
    protected double curLatitude=0.0;//纬度
    protected double curLongitude=0.0;//经度

    private static final int RC_LOCATION_CONTACTS_PERM = 124;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;


    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    private WeakReference<AMapLocationListener> ref;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        TAG = this.getClass().getSimpleName();
        mActivity = getActivity();
        LogUtil.i(TAG + "------" + "onAttach");
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isResumed()) {
            handleOnVisibilityChangedToUser(isVisibleToUser);
        }
        LogUtil.i(TAG + "------" + "setUserVisibleHint");
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LogUtil.i(TAG + "------" + "onCreate");
//        EventBus.getDefault().register(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // 避免多次从xml中加载布局文件
        LogUtil.i(TAG + "------" + "onCreateView");
        return super.onCreateView(inflater, container, savedInstanceState);
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        LogUtil.i(TAG + "------" + "onActivityCreated");
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        LogUtil.i(TAG + "------" + "onCreateView");
    }

    @Override
    public void onStart() {
        super.onStart();
        LogUtil.i(TAG + "------" + "onStart");
    }
    @Override
    public void onResume() {
        super.onResume();
        LogUtil.i(TAG + "------" + "onResume");

    }

    @Override
    public void onPause() {
        super.onPause();
        LogUtil.i(TAG + "------" + "onPause");
    }
    @Override
    public void onStop() {
        super.onStop();
        LogUtil.i(TAG + "------" + "onStop");
    }
    @Override
    public void onDetach() {
        super.onDetach();
        LogUtil.i(TAG + "------" + "onDetach");
    }




    @Override
    public void onDestroyView() {
        super.onDestroyView();
        LogUtil.i(TAG + "------" + "onDestroyView");
//        EventBus.getDefault().unregister(this);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtil.i(TAG + "------" + "onDestroy");
//        EventBus.getDefault().unregister(this);
        if (mLocationClient!=null) {
            mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
            mLocationClient = null;
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        LogUtil.i(TAG + "------" + "onHiddenChanged:"+hidden);
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        LogUtil.i(TAG + "------" + "onSupportVisible");
        //启动定位
        if (mLocationClient!=null) {
            mLocationClient.startLocation();
        }
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        LogUtil.i(TAG + "------" + "onSupportInvisible");
        stopDW();
    }

    public void ToastMessageShort(String message){
        Toast.makeText(getContext().getApplicationContext(),message, Toast.LENGTH_SHORT).show();
    }
    public void ToastMessageLong(String message){
        Toast.makeText(getContext().getApplicationContext(),message, Toast.LENGTH_LONG).show();
    }

    /**
     * 处理回退事件
     *
     * @return
     */
    @Override
    public boolean onBackPressedSupport() {
//        if (System.currentTimeMillis() - TOUCH_TIME < WAIT_TIME) {
//        _mActivity.pop();
//            _mActivity.finish();
//        } else {
//            TOUCH_TIME = System.currentTimeMillis();
//            Toast.makeText(_mActivity, R.string.press_again_exit, Toast.LENGTH_SHORT).show();
//        }
        return  super.onBackPressedSupport();
    }
    /**
     * 处理对用户是否可见
     *
     * @param isVisibleToUser
     */
    private void handleOnVisibilityChangedToUser(boolean isVisibleToUser) {
        if (isVisibleToUser) {
            // 对用户可见
            if (!mIsLoadedData) {
                mIsLoadedData = true;
                onLazyLoadOnce();
            }
            onVisibleToUser();
        } else {
            // 对用户不可见
            onInvisibleToUser();
        }
    }
    /**
     * 懒加载一次。如果只想在对用户可见时才加载数据，并且只加载一次数据，在子类中重写该方法
     */
    protected void onLazyLoadOnce() {
    }

    /**
     * 对用户可见时触发该方法。如果只想在对用户可见时才加载数据，在子类中重写该方法
     */
    protected void onVisibleToUser() {
    }

    /**
     * 对用户不可见时触发该方法
     */
    protected void onInvisibleToUser() {
    }
    /**
     * start other BrotherFragment
     */
//    @Subscribe
//    public void startBrother(StartBrotherEvent event) {
//        start(event.targetFragment);
//    }



    public void getJwd() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getContext().getApplicationContext());
//        ref=new WeakReference<AMapLocationListener>(mLocationListener);
//        AMapLocationListener refAMapLocationListener=ref.get();
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);

        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Battery_Saving，低功耗模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        mLocationOption.setHttpTimeOut(20000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        /**
         * 获取一次定位
         */
        //该方法默认为false，true表示只定位一次
        mLocationOption.setOnceLocation(false);
//        mLocationOption.setInterval(10000);
        mLocationClient.startLocation();

    }

    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {

        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            // TODO Auto-generated method stub
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //可在其中解析amapLocation获取相应内容。
                    double locationType = amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    curLatitude = amapLocation.getLatitude();//获取纬度
                    curLongitude = amapLocation.getLongitude();//经度
//                    setCurLatitude(curLatitude);
//                    setCurLongitude(curLongitude);
                    SPUtils.put(getContext(),"curLatitude",curLatitude);
                    SPUtils.put(getContext(),"curLongitude",curLongitude);
                    LogUtil.i(TAG+",Amap==经度：纬度", "locationType:" + locationType + ",curLatitude:" + curLatitude + ",curLongitude" + curLongitude);

                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    LogUtil.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };




    @AfterPermissionGranted(RC_LOCATION_CONTACTS_PERM)
    public void locationAndContactsTask() {
        String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
        if (EasyPermissions.hasPermissions(getContext().getApplicationContext(), perms)) {
            // Have permissions, do the thing!
            getJwd();
        } else {
            // Ask for both permissions
            EasyPermissions.requestPermissions(this, getString(R.string.rationale_location_contacts),
                    RC_LOCATION_CONTACTS_PERM, perms);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // EasyPermissions handles the request result.
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        LogUtil.i(TAG, "onPermissionsGranted:" + requestCode + ":" + perms.size());
        getJwd();
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        LogUtil.i(TAG, "onPermissionsDenied:" + requestCode + ":" + perms.size());
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }
    public void stopDW(){
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
        }
    }
}
